﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml;
using System.IO;
using System.Management;
using nVentive.Umbrella.Extensions;
using HyperVMover;

namespace VMMove.Business
{
    public class VirtualMachine
    {
        private readonly string _hyperVRootPath = 
            Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                @"Microsoft\Windows\Hyper-V");

        public VirtualMachine(string vmFile)
        {
            ConfigurationPath = vmFile;

            try
            {
                using (var reader = XmlTextReader.Create(File.Open(vmFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)))
                {
                    // The file may be locked by Hyper-V, but we can still open it by using Read/Write sharing
                    var document = XDocument.Load(reader);

                    RealName = document.XPathSelectElement("/configuration/properties/name").Value;
                    Name = RealName;
                }

                UpdateState();
            }
            catch (Exception)
            {
                Name = System.IO.Path.GetFileName(vmFile);
            }
        }

        private void UpdateState()
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization", null);
            ManagementObject vm = Utility.GetTargetComputer(RealName, scope);

            State = (VMState)Convert.ToInt32(vm.GetPropertyValue("EnabledState"));
        }

        public string ConfigurationPath { get; private set; }

        public string RealName { get; private set; }
        public string Name { get; private set; }

        public VMState State { get; private set; }
    }
}
